package com.leetcode.August;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description: 637二叉树的层平均值
 * @Author: Mr.Fxy
 * @CreateTime: 2024-08-22 16:16
 */
public class LC637二叉树的层平均值 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> avg=new ArrayList<>();
        if (root==null || root.left==null && root.right==null)return avg;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            double sum=0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum+=node.val;
                if (node.left!=null)queue.offer(node.left);
                if (node.right!=null)queue.offer(node.right);
            }
            avg.add(sum/size);
        }
        return avg;
    }
}
